package com.jiangnan.exception;


import com.jiangnan.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result HandleException(Exception e) {
        log.error("服务器异常：", e);
        return Result.error("服务器异常: " + e.getMessage());
    }

    @ExceptionHandler
    public Result HandleDuplicateKeyException(DuplicateKeyException e) {
        log.error("业务异常：", e);
        String msg = e.getMessage();
        int index = msg.indexOf("Duplicate entry");
        String errMsg = msg.substring(index);
        String[] split = errMsg.split(" ");
        String errorMsg = split[2] + "已存在";
        return Result.error(errorMsg);
    }


}
